package com.example.interesting.distributed.lock.test.service;

import com.example.interesting.distributed.lock.realize.DistributedLockTemplate;
import com.example.interesting.distributed.lock.realize.annotation.DistributedLockAnnotation;
import com.example.interesting.distributed.lock.realize.entity.DistributedLockInfo;
import com.example.interesting.distributed.lock.test.dto.UserDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author fyw
 * @version 1.0
 * @description: TODO
 * @date 2024/3/17 14:35
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LockServiceImpl implements LockService {

    private final DistributedLockTemplate distributedLockTemplate;


    @Override
    public void programmaticLocking() {
        DistributedLockInfo lockInfo = null;
        try {
            lockInfo = distributedLockTemplate.lock("programmaticLocking", 1000, 10000, null);
            if (lockInfo == null) {
                throw new RuntimeException("获取锁失败");
            }
            log.info("程序化锁获取成功");
            //模拟业务逻辑;
            Thread.sleep(3000);
        } catch (Exception e) {
            log.error("程序化锁异常", e);
        } finally {
            if (lockInfo != null) {
                boolean b = distributedLockTemplate.releaseLock(lockInfo);
                log.info("程序化锁释放结果:{}", b);
            }
        }

    }

    @Override
    @DistributedLockAnnotation(name = "annotationLocking", acquireTimeout = 1000, expire = 10000, failMsg = "业务处理中", keys = {"#userDTO.id", "#userDTO.name"})
    public void annotationLocking(UserDTO userDTO) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
